#include <iostream>
#include <string>
#include <fstream>
#include <list>
#include <ctime>
int main() {
    std::list<int> test;
    std::ifstream ifs("linear_data_structure_experiment.txt");
    if(!ifs.is_open()) {
        std::cout << "Failed to open file." << std::endl;
        return 1;
    }
    int temp;
    int count = 0;
    std::cout<<"Read txt to List"<<std::endl;
    while(ifs>>temp)
    {
        
         if(temp == 0)
        {
            count++;
            // std::cout<<"发现 "<<count<<" 个0元素"<<std::endl;
        }
        test.push_back(temp);
    }
    auto it = test.begin();
    std::cout << "在0元素前插入-1" << std::endl;
    clock_t start1 = clock();
    while(it != test.end()){
        if(*it == 0){
            it = test.insert(it,-1);
            ++it;//只能通过++移动迭代器
            ++it;
        }
        //不是0,直接移动到下一个元素
        else ++it;
    }
    std::cout<<"此时list有 "<<test.size()<<" 个元素"<<std::endl;
    count = 0;
    clock_t end1 = clock();
    std::cout<<"在所有“0”元素之前插入“-1”操作 花费: "<<(double)(end1-start1)/CLOCKS_PER_SEC<<" 秒\n";
    clock_t start2 = clock();
    it = test.begin();
    while (it != test.end()) {
        if (*it == 0) {
            count++;
            it = test.erase(it);  // 直接用返回的迭代器继续
            // std::cout << "删除 " << count << " 个0元素" << std::endl;
        } else {
            ++it;  // 非0元素才移动迭代器
        }
    }

    clock_t end2 = clock();
    std::cout<<"此时list有 "<<test.size()<<" 个元素"<<std::endl;
    std::cout<<"删除所有“0”元素操作 花费: "<<(double)(end2-start2)/CLOCKS_PER_SEC<<" 秒\n";
    std::cout<<"总耗时: "<<(double)(end2-start1)/CLOCKS_PER_SEC<<" 秒\n";
    return 0;
}